package com.youhome.service.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.config.OSSConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.HouseVideoMapper;
import com.youhome.service.model.HouseVideo;
import com.youhome.service.service.HouseVideoService;
import com.youhome.utils.HttpClientUtils;
import com.youhome.utils.SignUtils;
import com.youhome.utils.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.*;

/**
 * Created by chen365 on 2019/01/17.
 */
@Service
public class HouseVideoServiceImpl implements HouseVideoService {
    @Autowired
    private HouseVideoMapper houseVideoMapper;
    @Autowired
    private OSSConfig ossConfig;

    @Override
    public int deleteByPrimaryKey(String videoId) {
        return houseVideoMapper.deleteByPrimaryKey(videoId);
    }

    @Override
    public int insert(HouseVideo record) {
        return houseVideoMapper.insert(record);
    }

    @Override
    public int insertSelective(HouseVideo record) {
        return houseVideoMapper.insertSelective(record);
    }

    @Override
    public int updateByPrimaryKeySelective(HouseVideo record) {
        return houseVideoMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int selectCountByHouseId(String houseId) {
        return houseVideoMapper.selectCountByHouseId(houseId);
    }

    @Override
    public HouseVideo selectByPrimaryKey(String videoId) {
        return houseVideoMapper.selectByPrimaryKey(videoId);
    }

    @Override
    public List<HouseVideo> selectByBean(HouseVideo record) {
        return houseVideoMapper.selectByBean(record);
    }

    @Override
    public List<HouseVideo> selectByHouseId(String houseId) {
        return houseVideoMapper.selectByHouseId(houseId);
    }

    @Override
    public List<String> selectVideoUrlByHouseId(String houseId) {
        return houseVideoMapper.selectVideoUrlByHouseId(houseId);
    }

    /**
     * 定时查询更新视频转码状态
     */
    @Override
    public void TimedSearchUpdateVideoTransCodingStatus() {

        String accessKeyId = ossConfig.getAccessKeyId();
        String keySecret = ossConfig.getAccessKeySecret();

        //作业状态：
        //Submitted表示作业已提交，
        //Transcoding表示转码中，
        //TranscodeSuccess表示转码成功，
        //TranscodeFail表示转码失败，
        //TranscodeCancelled表示转码取消

        List<String> parameters = new ArrayList<>();
        parameters.add("Submitted");
        parameters.add("Transcoding");
        List<HouseVideo> list = houseVideoMapper.selectByStatus(parameters);
        for (HouseVideo item : list) {

            Map<String, String> parameterMap = new HashMap<>();
            // 加入请求公共参数
            parameterMap.put("Action", "QueryJobList");
            parameterMap.put("JobIds", item.getJobId());
            parameterMap.put("Version", "2014-06-18");
            parameterMap.put("AccessKeyId", accessKeyId);
            parameterMap.put("Timestamp", SignUtils.formatIso8601Date(new Date()));
            parameterMap.put("SignatureMethod", "HMAC-SHA1");
            parameterMap.put("SignatureVersion", "1.0");
            parameterMap.put("SignatureNonce", UUID.randomUUID().toString());
            parameterMap.put("Format", "JSON");

            try {
                String url = SignUtils.sign(keySecret, parameterMap);
                String json = HttpClientUtils.sendGet(url);
                if (!StringUtils.isEmpty(json)) {
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    JSONObject jobList = jsonObject.getJSONObject("JobList");
                    JSONArray jobs = jobList.getJSONArray("Job");
                    JSONObject job = jobs.getJSONObject(0);

                    String state = job.getString("State");
                    String finishTime = job.getString("FinishTime");
                    JSONObject output = job.getJSONObject("Output");
                    JSONObject properties = output.getJSONObject("Properties");
                    Double fileSize = properties.getDouble("FileSize");
                    String fileFormat = properties.getString("FileFormat");
                    Integer duration = properties.getInteger("Duration");
                    Integer height = properties.getInteger("Height");
                    Integer width = properties.getInteger("Width");
                    Integer fps = properties.getInteger("Fps");
                    Integer bitrate = properties.getInteger("Bitrate");

                    HouseVideo video = new HouseVideo();
                    video.setVideoId(item.getVideoId());
                    video.setStatus(state);
                    video.setFormat(fileFormat);
                    video.setDuration(duration);
                    video.setHeight(height);
                    video.setWidth(width);
                    video.setFps(fps);
                    video.setBitrate(bitrate);

                    if (!StringUtils.isEmpty(finishTime)) {
                        video.setFinishTime(DateUtils.parseDate(finishTime, new String[]{"yyyy-MM-dd'T'HH:mm:ss'Z'"}));
                    }
                    video.setVideoSize(fileSize);

                    houseVideoMapper.updateByPrimaryKeySelective(video);

                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 定时查询更新视频转码状态
     */
    @Override
    public void TimedSearchUpdateVideoTransCodingStatus(String jobId) {

//        作业状态：
//        Submitted表示作业已提交，
//        Transcoding表示转码中，
//        TranscodeSuccess表示转码成功，
//        TranscodeFail表示转码失败，
//        TranscodeCancelled表示转码取消
        Map<String, String> parameterMap = new HashMap<String, String>();
        // 加入请求公共参数
        parameterMap.put("Action", "QueryJobList");
        parameterMap.put("JobIds", jobId);
        parameterMap.put("Version", "2014-06-18");
        parameterMap.put("AccessKeyId", "LTAIcfXDvwDqTETw");
        //parameterMap.put("Timestamp", DateFormatUtils.format(new Date(),"YYYY-MM-DDThh:mm:ssZ"));
        parameterMap.put("Timestamp", SignUtils.formatIso8601Date(new Date()));
        parameterMap.put("SignatureMethod", "HMAC-SHA1");
        parameterMap.put("SignatureVersion", "1.0");
        parameterMap.put("SignatureNonce", UUID.randomUUID().toString());
        parameterMap.put("Format", "JSON");

        String keySecret = "z2vkfxsGTdys7zoPqNd0qnh8XRpWwI";
        try {
            String url = SignUtils.sign(keySecret, parameterMap);
            String json = HttpClientUtils.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(json);
            JSONObject jobList = jsonObject.getJSONObject("JobList");
            JSONArray jobs = jobList.getJSONArray("Job");
            JSONObject job = jobs.getJSONObject(0);
            String JobId = job.getString("JobId");
            String state = job.getString("State");
            String finishTime = job.getString("FinishTime");

            System.err.println("jobId:" + JobId);
            System.err.println("state:" + state);
            System.err.println("finishTime:" + finishTime);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    @Override
    public PageInfo<HouseVideo> selectByBean(Integer pageNumber, Integer pageSize, HouseVideo record) {
        if (StringUtils.isEmpty(pageNumber) || pageNumber < 1) {
            pageNumber = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize < 10) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<HouseVideo> houseVideos = houseVideoMapper.selectByBean(record);
        return new PageInfo<>(houseVideos);
    }

    @Override
    public void deleteByEnabled(String videoId) throws CustomException {
        if (StringUtils.isEmpty(videoId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        HouseVideo record = new HouseVideo();
        record.setVideoId(videoId);
        record.setEnabled(false);
        if (houseVideoMapper.updateByPrimaryKeySelective(record) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public List<HouseVideo> selectVideoByHouseId(String houseId) throws CustomException {

        if (StringUtils.isEmpty(houseId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        HouseVideo record = new HouseVideo();
        record.setHouseId(houseId);
        record.setEnabled(true);
        return houseVideoMapper.selectByBean(record);

    }

    @Override
    public PageInfo<HouseVideo> selectVideoByHouseId(String houseId, Integer pageNumber, Integer pageSize) throws CustomException {
        //作业状态：
        //Submitted表示作业已提交，
        //Transcoding表示转码中，
        //TranscodeSuccess表示转码成功，
        //TranscodeFail表示转码失败，
        //TranscodeCancelled表示转码取消
        if (StringUtils.isEmpty(houseId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        HouseVideo record = new HouseVideo();
        record.setStatus("TranscodeSuccess");
        record.setHouseId(houseId);
        record.setEnabled(true);

        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<HouseVideo> houseVideos = houseVideoMapper.selectByBean(record);
        return new PageInfo<>(houseVideos);
    }
}
